package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TradeProvinceOrderWindow;
import com.atguigu.gmall.realtime.function.DimAsyncFunction;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/5/20 15:53
 */
public class Dws_10_DwsTradeProvinceOrderWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_10_DwsTradeProvinceOrderWindowApp().init(
            "Dws_10_DwsTradeProvinceOrderWindowApp",
            4010,
            2,
            "Dws_10_DwsTradeProvinceOrderWindowApp",
            "Dws_10_DwsTradeProvinceOrderWindowApp",
            "dwd_trade_order_detail"
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 按照 order_detail_id 进行去重
        SingleOutputStreamOperator<JSONObject> disinctedStream = distinctByOrderDetailId(stream);
        // 2. 转换数据结构
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream = parseToBean(disinctedStream);
        // 3. 按照省份id分组开窗聚合
        SingleOutputStreamOperator<TradeProvinceOrderWindow> aggregatedStream = windowAngAgg(beanStream);
        // 4. 关联省份维度信息
        SingleOutputStreamOperator<TradeProvinceOrderWindow> resultStream = addDim(aggregatedStream);
        // 5. 写出到 clickHouse 数据库中
        // 省略
        
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> addDim(SingleOutputStreamOperator<TradeProvinceOrderWindow> steam) {
       return AsyncDataStream.unorderedWait(
            steam,
            new DimAsyncFunction<TradeProvinceOrderWindow>() {
                @Override
                protected void addDim(JSONObject dim,
                                      TradeProvinceOrderWindow input) throws Exception {
                    String provinceName = dim.getString("NAME");
                    input.setProvinceName(provinceName);
                }
    
                @Override
                protected String getId(TradeProvinceOrderWindow input) {
                    return input.getProvinceId();
                }
    
                @Override
                protected String getTableName() {
                    return "dim_base_province";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> windowAngAgg(
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeProvinceOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            
            
            )
            .keyBy(TradeProvinceOrderWindow::getProvinceId)
            .window(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public TradeProvinceOrderWindow reduce(TradeProvinceOrderWindow tow1,
                                                           TradeProvinceOrderWindow tow2) throws Exception {
                        tow1.setOrderAmount(tow1.getOrderAmount() + tow2.getOrderAmount());
                        tow1.getOrderIdSet().addAll(tow2.getOrderIdSet());
                        return tow1;
                    }
                },
                new ProcessWindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeProvinceOrderWindow> elements,
                                        Collector<TradeProvinceOrderWindow> out) throws Exception {
                        TradeProvinceOrderWindow bean = elements.iterator().next();
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
                        bean.setStt(DateFormatUtil.toYmdHms(ctx.window().getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
    
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> parseToBean(
        SingleOutputStreamOperator<JSONObject> disinctedStream) {
        return disinctedStream
            .map(jsonObj -> {
                String provinceId = jsonObj.getString("province_id");
                String orderId = jsonObj.getString("order_id");
                Double orderAmount = jsonObj.getDouble("split_total_amount");
                Long ts = jsonObj.getLong("ts") * 1000L;
                
                return TradeProvinceOrderWindow.builder()
                    .provinceId(provinceId)
                    .orderIdSet(new HashSet<>(Collections.singleton(orderId)))
                    .orderAmount(orderAmount)
                    .ts(ts)
                    .build();
                
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getLong("id"))
            .process(new KeyedProcessFunction<Long, JSONObject, JSONObject>() {
                // 存储数据最全的状态
                private ValueState<JSONObject> lastDataState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastDataState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastDataState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject data,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastData = lastDataState.value();
                    if (lastData == null) {
                        // 把数据存入到状态中, 并定义定时器
                        lastDataState.update(data);
                        
                        ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                    } else {
                        // 2022-05-08 15:30:56.723Z   row_op_ts":"2022-05-08 15:30:56.72Z
                        String currentTime = data.getString("row_op_ts");
                        String lastTime = lastData.getString("row_op_ts");
                        // 新数据的生成时间是否 大于 状态中的数据的生成时间
                        boolean isGreatOrEqual = AtguiguUtil.compareLTZ(currentTime, lastTime);
                        if (isGreatOrEqual) {
                            // 更新状态
                            lastDataState.update(data);
                        }
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<JSONObject> out) throws Exception {
                    out.collect(lastDataState.value());
                }
            });
    }
    
}
